import Vue from 'vue'
import Vuex from 'vuex'
import {sysUserApi} from '@/api/sys/SysUserApi'
import {sysMenuApi} from '@/api/sys/SysMenuApi'
import {getStore, setStore, toTreeData} from 'js-utils'
import staticRouter from '../router/staticRouter'
import router from '../router'
import {setMenu} from "@/utils/util";

Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    userInfo: {},
    menuList: [],
    permissions: [],
    size: getStore('size') || 'mini',
    isCollapse: false,
    initFlag: false,
    cacheMenuList: getStore("cacheMenuList") || [],
    borderImgList: []
  },
  actions: {
    getUserInfo({commit, state, dispatch}) {
      sysUserApi.info().then(res => {
        setStore('userInfo', res.data || null);
        state.userInfo = res.data || {};
        state.permissions = res.data.perms || [];
      })
        .catch(err => err)
    },
    listUserMenu: function ({commit, state, dispatch}) {
      return new Promise((resolve, reject) => {
        sysMenuApi.listUserMenu().then(res => {
          let menuList = res.data.filter(v => v.menuType < 2);
          state.menuList = setMenu(toTreeData(menuList, "0")).concat(staticRouter);
          state.initFlag = true;
          router.addRoutes([{
            path: '/',
            component: () => import('@/views/index'),
            children: state.menuList
          }]);
          resolve(res.data);
        })
          .catch(err => reject(err))
      })
    },
  },
  getters: {},
  mutations: {
    setSize(state, size) {
      state.size = size;
      setStore('size', size);
    },
    setCollapse(state) {
      state.isCollapse = !state.isCollapse;
    },
    logout(state) {
      setStore('token', null, true);
      setStore('cacheMenuList', null);
      state.initFlag = false;
      state.menuList = [];
      state.permissions = [];
      state.userInfo = {};
      state.cacheMenuList = [];
      router.replace("/login");
      // location.reload();
    },
    pushCacheMenu(state, data) {
      let isExist = state.cacheMenuList.find(v => v.path === data.path);
      if (isExist) return;
      state.cacheMenuList.push(data);
      setStore('cacheMenuList', state.cacheMenuList);
    },
    removeCacheMenu(state, path) {
      state.cacheMenuList = state.cacheMenuList.filter(v => v.path !== path);
      setStore('cacheMenuList', state.cacheMenuList);
    },
    removeAllCacheMenu(state) {
      state.cacheMenuList = [];
      setStore('cacheMenuList', null);
    },
  }
})
